package heap;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author justnow
 * Created on 2020-10-02
 * Description
 *
 * 最小的k个数
 */
public class SwardOffer40 {


    public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr == null || arr.length <= 0) {
            return new int[0];
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>((x1, x2) -> x2 - x1);
        int length = arr.length;
        for (int i = 0; i < length; i++) {
            if (i < k) {
                queue.offer(arr[i]);
            } else {
                try {
                    if (queue.peek() > arr[i]) {
                        queue.remove();
                        queue.offer(arr[i]);
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = queue.remove();
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2};
        int k = 2;
        SwardOffer40 swardOffer40 = new SwardOffer40();
        int[] leastNumbers = swardOffer40.getLeastNumbers(arr, k);
        System.out.println(Arrays.toString(leastNumbers));
    }
}
